package com.geng.io.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Echoclient {
    public static void main(String[] args) {
        int port = 9999;
        new Echoclient().connect(port,"127.0.0.1");
    }
    public void connect(int port,String host){
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
              b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<NioSocketChannel>() {

                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture f = b.connect(host,port).sync();
            byte[] req = "你好，netty".getBytes();
            ByteBuf msg = Unpooled.buffer(req.length);
            msg.writeBytes(req);
            Channel channel = f.channel();
            System.out.println(channel);
            ChannelFuture cf = channel.writeAndFlush(msg);
            cf.syncUninterruptibly();
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}
